package code.D1214;

import java.util.Stack;

/**
 * author : yeswater
 * date : 2023/12/14
 * 
 * 二叉树展开为链表
 * 
 */

public class T114 {
    // 递归
    private TreeNode pre;
    public void flatten(TreeNode root) {
        if(root == null) {
            return ;
        }
        flatten(root.right);
        flatten(root.left);
        root.right = pre;
        root.left = null;
        
        pre = root;
        
    }
    
    // 用 栈 暂存 
    public void flatten2(TreeNode root) {
        if (root == null) {
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode pre = null;
        while (!stack.isEmpty()) {
            TreeNode tmp = stack.pop();
            if (pre != null) {
                pre.right = tmp;
                pre.left = null;
            }
            
            if (tmp.right != null) {
                stack.push(tmp.right);
            }
            if (tmp.left != null) {
                stack.push(tmp.left);
            }
            pre = tmp;
        }
    }
    
    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        
        TreeNode() {
        }
        
        TreeNode(int val) {
            this.val = val;
        }
        
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
